import Head from "next/head";
import styles from "@/styles/question.module.css";
import { getQuestionById } from "@/services/question";
import PageWrapper from "@/components/PageWrapper/PageWrapper";
import QuestionInput from "@/components/QuestionComponents/QuestionInput";
import QuestionRadio from "@/components/QuestionComponents/QuestionRadio";
import { getComponent } from "@/components/QuestionComponents";

type PropsType = {
  errno: number;
  data?: {
    id: string;
    title: string;
    desc?: string;
    js?: string;
    css?: string;
    isPublished: boolean;
    isDeteted: boolean;
    componentList: Array<any>;
  };
  msg?: string;
};
export default function Question(props: PropsType) {
  const { errno, data, msg = "" } = props;
  if (errno != 0) {
    return (
      <PageWrapper title="错误">
        <h1>错误</h1>
        <p>{msg}</p>
      </PageWrapper>
    );
  }
  const {
    id,
    title = "",
    isDeteted,
    desc,
    isPublished,
    componentList,
  } = data || {};
  if (isDeteted) {
    return (
      <PageWrapper title="错误" desc={desc}>
        <h1>{title}</h1>
        <p>该问卷已经被删除</p>
      </PageWrapper>
    );
  }
  if (!isPublished) {
    return (
      <PageWrapper title="错误" desc={desc}>
        <h1>{title}</h1>
        <p>该问卷尚未发布</p>
      </PageWrapper>
    );
  }
  const ComponentListElem = <>
    {
      componentList?.map(c=>{
        const ComponentElem = getComponent(c)
        return <div key={c.fe_id} className={styles.componentWrapper}>
          {ComponentElem}
        </div>
      })
    }
  </>
  return (
    <PageWrapper title={title}>
      <form method="post" action="/api/answer">
        <input type="hidden" name="questionId" value={id} />
        {ComponentListElem}
        <div className={styles.sumbitBtnContainer}>
          <button type="submit">提交</button>
        </div>
      </form>
    </PageWrapper>
  );
}
export async function getServerSideProps(context: any) {
  const { id = "" } = context.params;
  const data = await getQuestionById(id);

  return {
    props: {
      ...data,
    },
  };
}
